package com.tangkun.environment.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tangkun.environment.R;
import com.tangkun.environment.application.Session;
import com.tangkun.environment.utils.DownLoadImageService;
import com.tangkun.environment.utils.ImageDownLoadCallBack;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.Utils;
import com.tangkun.environment.view.CircleImageView;

import java.io.File;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * 个人头像
 */

public class TouXiangActivity extends BaseActivity {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.civ_touxiang)
    CircleImageView civTouxiang;
    private PopupWindow popupWindow;

    private Context mContext;

    private final int REQUEST_CODE_PICK_IMAGE = 10;
    private final int REQUEST_CODE_CAPTURE_CAMEIA = 11;
    private final int REQUEST_CODE_CROP_IMAGE = 12;

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    private Uri tmpUri;
    private String tmpPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_tou_xiang);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        title.setText("个人头像");
        right.setImageResource(R.mipmap.more);
        right.setVisibility(View.VISIBLE);
        //头像
        //圆形裁剪
        Glide.with(mContext)
                .load(Session.getInstance().getResourceBaseUrl() + Session.getInstance().getUserHeadPicture())
                .bitmapTransform(new CropCircleTransformation(mContext))
                .placeholder(R.mipmap.ic_wrong_head)
                .into(civTouxiang);

        //初始化临时路径
        tmpUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
    }

    @OnClick({R.id.back, R.id.right, R.id.civ_touxiang})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                JumpHelper.finish(mContext);
                break;
            case R.id.right://更多
                bottomwindow(right);
                backgroundAlpha(0.5f);
                break;
            case R.id.civ_touxiang:
                bottomwindow(right);
                backgroundAlpha(0.5f);
                break;
        }
    }

    private void bottomwindow(View view) {
        if (popupWindow != null && popupWindow.isShowing()) {
            return;
        }
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.person_photo_popuwindows, null);
        popupWindow = new PopupWindow(layout,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //点击空白处时，隐藏掉pop窗口
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //添加弹出、弹入的动画
        popupWindow.setAnimationStyle(R.style.Popupwindow);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        popupWindow.showAtLocation(view, Gravity.LEFT | Gravity.BOTTOM, 0, -location[1]);
        //添加按键事件监听
        setListeners(layout);
        //添加pop窗口关闭事件，主要是实现关闭时改变背景的透明度
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
    }

    /**
     * popuwindows的监听事件
     *
     * @param layout
     */
    private void setListeners(LinearLayout layout) {
        TextView takePhoto = (TextView) layout.findViewById(R.id.takePhoto);
        TextView fromXiangCe = (TextView) layout.findViewById(R.id.from_xiangCe);
        TextView savepicture = (TextView) layout.findViewById(R.id.save_img);
        TextView cancel = (TextView) layout.findViewById(R.id.cancle_geRenTouXiang);

        //拍照
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    //调用系统相机拍照
                    popupWindow.dismiss();
                    makePhoto();
                }
            }
        });
        //相册
        fromXiangCe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    //在此处添加你的按键处理
                    popupWindow.dismiss();
                    takePhoto();
                }
            }
        });
        //保存图片
        savepicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    //在此处添加你的按键处理 xxx
                    popupWindow.dismiss();
                    //头像图片网络地址
                    String url = Session.getInstance().getResourceBaseUrl() + Session.getInstance().getUserHeadPicture();
                    //下载图片线程
                    DownLoadImageService downLoadImageService = new DownLoadImageService(mContext, url, new ImageDownLoadCallBack() {
                        @Override
                        public void onDownLoadSuccess(File file) {

                        }

                        @Override
                        public void onDownLoadSuccess(Bitmap bitmap) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showToast("保存成功");
                                }
                            });
                        }

                        @Override
                        public void onDownLoadFailed() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showToast("保存失败");
                                }
                            });
                        }
                    });
                    //启动图片下载线程
                    new Thread(downLoadImageService).start();
                }
            }
        });
        //取消
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    private static Uri getOutputMediaFileUri(int type) {
        File file = getOutputMediaFile(type);
        if (file == null) {
            return null;
        }
        return Uri.fromFile(file);
    }

    private static File getOutputMediaFile(int type) {
        if (!Utils.isSDState()) {
            return null;
        }
        File mediaStoreaDir = new File(Environment.getExternalStorageDirectory(), "EnvironmentApp");
        if (!mediaStoreaDir.exists()) {
            if (!mediaStoreaDir.mkdirs()) {
                return null;
            }
        }
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStoreaDir.getPath() + File.separator + "IMG_TEMP" + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStoreaDir.getPath() + File.separator + "VID_TIMP" + ".mp4");
        } else {
            return null;
        }
        if (mediaFile.exists()) {
            try {
                mediaFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mediaFile;
    }

    /**
     * 拍照
     */
    private void makePhoto() {
        if (tmpUri == null) {
            showToast("请插入内存卡");
            return;
        }
        final Intent intentTakePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intentTakePhoto.putExtra(MediaStore.EXTRA_OUTPUT, tmpUri);
        intentTakePhoto.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
        startActivityForResult(intentTakePhoto, REQUEST_CODE_CAPTURE_CAMEIA);
    }

    /**
     * 从相册选取
     */
    private void takePhoto() {
        Intent intentPic = new Intent();
        intentPic.setType("image/*");
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
//            intentPic.setAction(Intent.ACTION_GET_CONTENT);
//        } else {
//            intentPic.setAction(Intent.ACTION_OPEN_DOCUMENT);
//            intentPic.addCategory(Intent.CATEGORY_OPENABLE);
//        }
        intentPic.setAction(Intent.ACTION_GET_CONTENT);
        intentPic.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(Intent.createChooser(intentPic, "头像选择"), REQUEST_CODE_PICK_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_PICK_IMAGE) {
                // 从相册取图片
                if (data != null) {
                    if (data.getData() != null) {
                        Uri uri = data.getData();
                        String string = Utils.getPath(this, uri);
                        if (string != null && !"".equals(string)) {
                            System.gc();
                            Intent intent = new Intent();
                            intent.setClass(this, CropImageActivity.class);
                            intent.putExtra("uri", string);
                            startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
                        } else {
                            showToast("获取照片失败");
                        }
                    } else {
                        showToast("获取照片失败");
                    }
                }
            } else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA) {
                // 拍照
                if (tmpUri == null) {
                    tmpUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
                }
                String string = Utils.getPath(this, tmpUri);
                if (string != null && !"".equals(string)) {
                    System.gc();
                    Intent intent = new Intent();
                    intent.setClass(this, CropImageActivity.class);
                    intent.putExtra("uri", string);
                    startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
                } else {
                    showToast("获取照片失败");
                }
            } else if (requestCode == REQUEST_CODE_CROP_IMAGE) {
                tmpPath = data.getStringExtra("backurl");
                if (tmpPath != null) {
                    //上传服务器
                    LogUtils.e("图片地址：" + tmpPath);
//                    sendPhotoToServer(tmpPath);
                } else {
                    showToast("返回裁剪图片出错");
                }
            }
        }
    }

//    /**
//     * 上传图片到服务器
//     *
//     * @param filePath 本地图片路径
//     */
//    private void sendPhotoToServer(String filePath) {
//        String[] filePathArray = filePath.split("/");
//        //文件名
//        String fileName = filePathArray[filePathArray.length - 1];
//        //生成文件
//        File file = new File(filePath);
//        //组装partMap对象
//        Map<String, RequestBody> partMap = new HashMap<>();
//        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), file);//文件
//        partMap.put("file\"; filename=\"" + fileName + "", fileBody);//文件名
//        RequestBody dirBody = RequestBody.create(MediaType.parse("text/plain"), "user/header");//dir参数值
//        RequestBody fileNameBody = RequestBody.create(MediaType.parse("text/plain"), fileName);//文件名参数值
//        partMap.put("dir", dirBody);//dir参数
//        partMap.put("fileName", fileNameBody);//dir参数
//        fromNetwork.upload(partMap).compose(new RxActivityHelper<UploadResourceReturn>().ioMain(TouXiangActivity.this, true))
//                .subscribe(new MySubscribe<UploadResourceReturn>(mContext, true) {
//                    @Override
//                    protected void success(UploadResourceReturn uploadResourceReturn) {
//                        if (uploadResourceReturn.result != null) {
//                            //头像地址
//                            String headPicture = uploadResourceReturn.result.fileRelativePath;
//                            updateInfo(headPicture);
//                        }
//                    }
//
//                    @Override
//                    protected void onMyError(String errorMessage) {
//                        showToast(errorMessage);
//                    }
//                });
//    }
//
//    /**
//     * 更新个人信息
//     *
//     * @param headPicture 头像地址
//     */
//    private void updateInfo(final String headPicture) {
//        Map<String, String> map = new HashMap<String, String>();
//        map.put("id", Session.getInstance().getUserId());
//        map.put("headPicture", headPicture);
//        fromNetwork.updateInfo(map).compose(new RxActivityHelper<CommonReturn>().ioMain(TouXiangActivity.this, true))
//                .subscribe(new MySubscribe<CommonReturn>(mContext, true) {
//                    @Override
//                    protected void success(CommonReturn commonRetrun) {
//                        showToast("修改成功");
//                        //替换Session中的头像地址
//                        Session.getInstance().getUserInfo().headPicture = headPicture;
//                        //圆形裁剪
//                        Glide.with(mContext)
//                                .load(Session.getInstance().getResourceBaseUrl() + Session.getInstance().getUserHeadPicture())
//                                .bitmapTransform(new CropCircleTransformation(mContext))
//                                .placeholder(R.mipmap.ic_wrong_head)
//                                .into(civTouxiang);
//                    }
//
//                    @Override
//                    protected void onMyError(String errorMessage) {
//                        showToast(errorMessage);
//                    }
//                });
//    }
}
